from crcmod import crcmod
def mycrc(command):
    tx=command.copy()
    crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
    crc_calc = crc16(bytes(command))  # 计算得到的CRC
    b = crc_calc % 256
    c = crc_calc // 256
    tx.append(b)
    tx.append(c)
    return tx

def SumCheck(data,length):
    '''
    char_checksum 按字节计算校验和。
    '''
    checksum = 0
    for i in range(0, length):
        checksum += data[i]
        checksum &= 0xFF  # 强制截断
    return checksum

def dataverify(data,len):
    try:
        if(len==data[3]):
            # if(data[0] == 0x51 & data[1] == 0x48 & data[len - 1] == 0xda):
            if((data[0] == 0x51)&(data[1] == 0x48)&(data[len - 1] == 0xda)):
                if (SumCheck(data, len - 2) == data[len - 2]):
                    return 1
    except:return 0


def HexStrAddSpace(HexStr):
    out_data = ''
    for i,s in enumerate(HexStr):
        if((i%2 == 0)&(i>0)):
            out_data += ' '
            out_data += s
        else:
            out_data += s
    return out_data.upper()
